import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { ResultData } from 'src/common/utils/result';
import { NotifyInfoEntity } from './entities/notify-info.entity';
import { NotifyInfoFilesEntity } from './entities/notify-info-files.entity';
import { CreateNotifyDto, ListNotifyDto, UpdateNotifyDto } from './dto/index';

@Injectable()
export class NotifyService {
  constructor(
    @InjectRepository(NotifyInfoEntity)
    private readonly notifyRepo: Repository<NotifyInfoEntity>,
    @InjectRepository(NotifyInfoFilesEntity)
    private readonly notifyFilesRepo: Repository<NotifyInfoFilesEntity>,
  ) {}

  async create(createNotifyDto: CreateNotifyDto) {
    // 创建通知信息
    const notify = new NotifyInfoEntity();
    notify.notifyType = createNotifyDto.notify_type;
    notify.orgId = createNotifyDto.org_id;
    notify.prjId = createNotifyDto.prj_id;
    notify.sn = createNotifyDto.sn;
    notify.taskType = createNotifyDto.task_info.task_type;
    notify.tags = createNotifyDto.task_info.tags.join(',');
    notify.taskId = createNotifyDto.task_info.task_id;
    notify.expectedFileCount = createNotifyDto.folder_info.expected_file_count;
    notify.uploadedFileCount = createNotifyDto.folder_info.uploaded_file_count;
    notify.folderId = createNotifyDto.folder_info.folder_id;

    const savedNotify = await this.notifyRepo.save(notify);

    // 创建文件记录
    const files = createNotifyDto.files.map(file => {
      const notifyFile = new NotifyInfoFilesEntity();
      notifyFile.notifyId = savedNotify.id;
      notifyFile.name = file.name;
      notifyFile.key = file.key;
      return notifyFile;
    });

    await this.notifyFilesRepo.save(files);

    return ResultData.ok();
  }

  async findAll(query: ListNotifyDto) {
    const queryBuilder = this.notifyRepo.createQueryBuilder('notify')
      .leftJoinAndSelect('notify.files', 'files')
      .where('1 = 1');

    if (query.notify_type) {
      queryBuilder.andWhere('notify.notifyType = :notifyType', { notifyType: query.notify_type });
    }

    if (query.org_id) {
      queryBuilder.andWhere('notify.orgId = :orgId', { orgId: query.org_id });
    }

    if (query.task_id) {
      queryBuilder.andWhere('notify.taskId = :taskId', { taskId: query.task_id });
    }

    if (query.pageNum && query.pageSize) {
      queryBuilder.skip((query.pageNum - 1) * query.pageSize)
        .take(query.pageSize);
    }

    const [list, total] = await queryBuilder.getManyAndCount();

    return ResultData.ok({
      list,
      total
    });
  }

  async findOne(id: number) {
    const notify = await this.notifyRepo.findOne({
      where: { id },
      relations: ['files']
    });
    return ResultData.ok(notify);
  }

  async remove(ids: number[]) {
    await this.notifyRepo.delete(ids);
    return ResultData.ok();
  }

  async update(updateNotifyDto: UpdateNotifyDto) {
    const notify = await this.notifyRepo.findOne({
      where: { id: updateNotifyDto.id },
      relations: ['files']
    });

    if (!notify) {
      return ResultData.fail(500, '通知不存在');
    }

    // 更新通知基本信息
    notify.notifyType = updateNotifyDto.notify_type;
    notify.orgId = updateNotifyDto.org_id;
    notify.prjId = updateNotifyDto.prj_id;
    notify.sn = updateNotifyDto.sn;
    notify.taskType = updateNotifyDto.task_info.task_type;
    notify.tags = updateNotifyDto.task_info.tags.join(',');
    notify.taskId = updateNotifyDto.task_info.task_id;
    notify.expectedFileCount = updateNotifyDto.folder_info.expected_file_count;
    notify.uploadedFileCount = updateNotifyDto.folder_info.uploaded_file_count;
    notify.folderId = updateNotifyDto.folder_info.folder_id;

    await this.notifyRepo.save(notify);

    // 删除旧的文件记录
    await this.notifyFilesRepo.delete({ notifyId: notify.id });

    // 创建新的文件记录
    const files = updateNotifyDto.files.map(file => {
      const notifyFile = new NotifyInfoFilesEntity();
      notifyFile.notifyId = notify.id;
      notifyFile.name = file.name;
      notifyFile.key = file.key;
      return notifyFile;
    });

    await this.notifyFilesRepo.save(files);

    return ResultData.ok();
  }
} 